#include "../include/muduo/net/TcpServer.h"
#include "../include/muduo/net/EventLoop.h"
#include "../include/muduo/net/Buffer.h"
#include "../include/muduo/net/TcpConnection.h"
#include <iostream>
#include <unordered_map>

class TranslateServer
{
private:
    muduo::net::TcpServer _server;  //服务器
    muduo::net::EventLoop _baseloop;   //用于事件监控
private:
    //这个函数在连接建立和连接断开都会被调用
    void OnConnected(const muduo::net::TcpConnectionPtr&conn){
        if(conn->connected() == true){
            std::cout << "新连接建立成功! \n";
        }else{
            std::cout << "连接断开 \n";
        }
    }

    std::string Translate(const std::string &text){
        static std::unordered_map<std::string,std::string> dict{
            {"hello","你好"},
            {"yes","是的"},
            {"red","红色"}
        };

        auto it = dict.find(text);
        if(it == dict.end()){
            return "UnKonw";
        }

        return it->second;
    }

    //这个函数会在服务器收到消息时调用
    void OnMessage(const muduo::net::TcpConnectionPtr& conn,muduo::net::Buffer* buf,muduo::Timestamp){
        //接收缓冲区取的数据
        std::string text = buf->retrieveAllAsString();
        //进行业务处理
        std::string ret = Translate(text);
        //发送给客户端
        conn->send(ret);
    }
public:
    TranslateServer(int port):
    _server(&_baseloop,
            muduo::net::InetAddress("0.0.0.0",port),
            "translateServer",
            muduo::net::TcpServer::Option::kNoReusePort)
    {
        //设置对应事件触发的回调函数
        _server.setConnectionCallback(std::bind(&TranslateServer::OnConnected,this,std::placeholders::_1));
        _server.setMessageCallback(std::bind(&TranslateServer::OnMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
    }
    //运行服务器
    void Start(){
        _server.start();    //开启监听套接字读监控,创建从属线程并启动
        _baseloop.loop();   //开始事件监控
    }
};

int main(){
    TranslateServer server(8888);
    server.Start();
}